#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h>
#include "dbConnector.h"

DBConnector::DBConnector(const char* host, const char* user, const char* password, const char* db)
{
	connector = NULL;
	this->user = strdup(user);
	this->password = strdup(password);
	this->host = strdup(host);
	this->db = strdup(db);
}

DBConnector::~DBConnector()
{
	if (connector != NULL)
		mysql_close(connector);
		
	if (user != NULL) free(user);
	if (password != NULL) free(password);
	if (host != NULL) free(host);
	if (db != NULL) free(db);
}

bool DBConnector::open()
{
	if (connector == NULL)
	{
		connector = mysql_init(NULL);
		if ( mysql_real_connect(connector, host, user, password, 
				NULL, 0, NULL, 0) == NULL) 
		{
			printf("MYSQL: %s\n", mysql_error(connector));
			return false;
		}

		if (mysql_select_db(connector, db) != 0)
		{
			printf("DB: %s\n", mysql_error(connector));
			return false;
		}
		
		return true;
	}
	
	else return false;
}

void DBConnector::close()
{
	if (connector != NULL)
	{
		mysql_close(connector);
		connector = NULL;
	}
}

MYSQL_RES* DBConnector::query(const char* command)
{
	MYSQL_RES* res;
	
	if (mysql_query(connector, command) != 0) 
	{
    	printf("MYSQL QUERY:\n%s\nCOMMAND:\n%s\n", mysql_error(connector), command);
		res = NULL;
   	}
	
	else
	{
		res = mysql_store_result(connector);
	}
	
	return res;
}

bool DBConnector::update(const char* command)
{	
	if (mysql_query(connector, command) != 0) 
	{
    	printf("MYSQL UPDATE:\n%s\nCOMMAND:\n%s\n", mysql_error(connector), command);
		return false;
   	}
	
	return true;
}

int DBConnector::getUID(const char* table, const char* col)
{
	MYSQL_ROW row;
	MYSQL_RES* res;
	int devolucion = -1;
	
	char* command = (char*)malloc(256*sizeof(char));
	sprintf(command, "select max(%s)+1 from %s", col, table);
	
	res = query(command);
	
	if (res != NULL)
	{
		if ((row = mysql_fetch_row(res)) != NULL)
			devolucion = atoi(row[0]);
		
		else devolucion = 0;
		
		mysql_free_result(res);
	}
	
	free(command);
	
	return devolucion;
}


